package com.harvey.guava.concurrent;

import com.google.common.util.concurrent.Monitor;

import java.util.LinkedList;

/**
 * @author harvey
 * @Description
 * @date 2020-03-30 10:40
 * @since
 */

public class MonitorExample {

    public static void main(String[] args) {



    }


    static class MonitorGuard {

        private final LinkedList<Integer> queue = new LinkedList<>();

        private final int MAX = 10;

        private final Monitor monitor = new Monitor();

        private final Monitor.Guard CAN_OFFER = monitor.newGuard(() -> queue.size() < MAX);
        private final Monitor.Guard CAN_TAKE = monitor.newGuard(() -> !queue.isEmpty());


        private void offer(int value) {
            try {
                monitor.enterWhen(CAN_OFFER);
                queue.addLast(value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                monitor.leave();
            }
        }

        private int take() {
            int value = 0;
            try {
                monitor.enterWhen(CAN_TAKE);
                value = queue.removeFirst();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                monitor.leave();
            }
            return value;
        }

    }


}
